package com.logic.modular.game.player.match;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class TaskExecutor {

    private static final int BATCH_SIZE = 1000;
    private static final ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public static void main(String[] args) {

        AtomicInteger threadCount = new AtomicInteger(1);
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5, r -> {
            Thread thread = new Thread(r);
            thread.setName("Custom-Scheduled-Thread-" + threadCount.getAndIncrement());
            thread.setDaemon(true); // 设置为守护线程
            return thread;
        });

        for (int i = 0; i < 1000000; i++) {
            int taskIndex = i;
            threadPoolExecutor.submit(() -> {
                try {
                    moveTask(scheduledThreadPoolExecutor, taskIndex, 1000);
                } catch (Exception e) {
                    // 记录异常日志或其他处理措施
                    System.err.println("Task " + taskIndex + " failed: " + e.getMessage());
                }
            });
        }

        // threadPoolExecutor.shutdown();
        // try {
        //     if (!threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
        //         threadPoolExecutor.shutdownNow();
        //     }
        // } catch (InterruptedException e) {
        //     threadPoolExecutor.shutdownNow();
        // }
    }

    // 假设moveTask是一个未实现的方法
    private static void moveTask(ScheduledExecutorService scheduledThreadPoolExecutor, int index, int move) {
        AtomicInteger atomicInteger = new AtomicInteger(move);
        // 实现具体的任务逻辑
        scheduledThreadPoolExecutor.scheduleAtFixedRate(()->{
            int i = atomicInteger.get();
            i--;
            atomicInteger.set(i);
            System.out.println("Task " + index + " moved " + atomicInteger);
        }, 0, 1, TimeUnit.SECONDS);
    }
}
